package com.hexinfo.dmpro.sparing.service.impl;


import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.file.FileAppender;
import com.hexinfo.dmpro.common.utils.ConnExecuteUtil;
import com.hexinfo.dmpro.component.comparison.service.ITableContrastService;
import com.hexinfo.dmpro.sparing.dto.DistCPDTO;
import com.hexinfo.dmpro.sparing.dto.HdfsDistcpDTO;
import com.hexinfo.dmpro.sparing.service.DistCPService;
import com.hexinfo.dmpro.sparing.service.HdfsDistCPService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.Statement;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Service
@Slf4j
public class HdfsDistCPServiceImpl implements HdfsDistCPService {

    @Value("${hdfs.heatBackup}")
    private String heatBackup;

    //hdfs热备完成数量
    private Map<String, Integer> statusMap = new ConcurrentHashMap<String, Integer>();
    @Override
    public synchronized void updateStatus(String uuidKey) {
        statusMap.put(uuidKey, 0);
    }
    private synchronized void addStatus(String uuidKey) {
        statusMap.put(uuidKey, statusMap.get(uuidKey)+1);
    }
    @Override
    public Integer getSize(String uuidKey) {
        return statusMap.get(uuidKey);
    }
    @Override
    public synchronized void delStatus(String uuidKey) {
        statusMap.remove(uuidKey);
    }

    @Override
    @Async("threadPoolTaskExecutor")
    public void execShell(HdfsDistcpDTO hdfsDistcpDTO, String uuid,FileAppender heatlog) {
        String shellTar = heatBackup + " " + hdfsDistcpDTO.getSouToTar();
        //第二步：源--》目标
        int b = ConnExecuteUtil.execShellCode(shellTar);
        if (b == 999){
            logLog(heatlog,"dsitcp执行错误shell：" + shellTar,true);
        }
        // 更新指定表完成情况
        addStatus(uuid);
    }

    /**
     * 加锁，防止并发问题
     * @param heatlog
     * @param logStr
     * @param state
     */
    private synchronized void logLog(FileAppender heatlog, String logStr ,boolean state) {
        if (state){
            heatlog.append(logTime(logStr));
        }else {
            heatlog.flush();     //刷进日志中
        }
    }

    /**
     * 日志加日期时间
     * @param str
     * @return
     */
    private String logTime(String str) {
        return "["+DateUtil.format(DateUtil.date(), "yyyy-MM-dd HH:mm:ss")+"]" +str;
    }

}
